package com.situ.ymall.admin.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.situ.ymall.admin.entity.Root;
import com.situ.ymall.admin.mapper.RootMapper;
import com.situ.ymall.admin.service.RootService;
import com.situ.ymall.admin.util.MD5Util;

@Service
public class RootServiceImpl implements RootService{
	@Autowired
	private RootMapper rootMapper;
	
	@Override
	public Root login(Root root) throws Exception {
		//1.账号密码格式是否正确
		if (root.getRootname() == null ||
				root.getRootname().length() < 3 ||
				root.getRootname().length() > 16) {
			throw new Exception("账号格式不对");
		}
		if (root.getPassword() == null ||
				root.getPassword().length() < 3 ||
				root.getPassword().length() > 16) {
			throw new Exception("密码格式不对");
		}
		// 2.查询账号信息
		Root selectRoot = rootMapper.selectByRootName(root.getRootname());
		// 3.判断账号是否存在
		if (selectRoot == null) {
			throw new Exception("账号不存在");
		}
		// 4.判断密码是否正确
		if (!selectRoot.getPassword().equals(MD5Util.getMD5(root.getPassword()))) {
			throw new Exception("密码错误");
		}
		// 5.判断账号是否可用
		if (selectRoot.getStatus() != 0) {
			throw new Exception("账号被禁用");
		}
		// 6.返回root
		return selectRoot;
	}

	@Override
	public Root getByRootName(String rootName) {
		return rootMapper.selectByRootName(rootName);
	}

	@Override
	public Root selectById(Integer id) {
		return rootMapper.selectByPrimaryKey(id);
	}

	@Override
	public Root edit(Root root) throws Exception {
		//判断旧密码是否正确
		Root selectRoot = rootMapper.selectByPrimaryKey(root.getId());
		if ( ! selectRoot.getPassword().equals(MD5Util.getMD5(root.getOldpassword()))){
			throw  new Exception("旧密码有误！");
		}
		// 修改
		if (root.getHead()== null || root.getHead().length() < 1 ){
			root.setHead(null);
		}
		root.setPassword(MD5Util.getMD5(root.getPassword()));
		rootMapper.updateByPrimaryKey(root);
		return rootMapper.selectByPrimaryKey(root.getId());
	}

}
